import axios from "axios";

export const Method = {
  GET: "GET",
  PUT: "PUT",
  DELETE: "DELETE",
  POST: "POST",
}

/**
 * 封装内部请求，请求借口
 * @param method 请求方法
 * @param api api路径
 * @param data 请求参数
 * @param host 默认http://www.alpha.daofengdj.com ，赋值后变更
 * @param headers 默认 {
    "content-type": "application/json",
  }
 * @returns  json对象
 */
export const launch = async (
  method,
  api,
  data,
  host,
  headers = {
    "content-type": "application/json",
  }
) => {
  switch (method) {
    case Method.PUT: {
      let res = await axios.put(`${host}${api}`, data, {
        headers
      });
      return res.data;
    }
    case Method.DELETE: {
      let res = await axios.delete(`${host}${api}?${encodeURI(data)}`, {
        method: Method.DELETE,
      });
      return res.data;
    }
    case Method.POST: {
      if (!headers["content-type"].includes("multipart")) {
        data = JSON.stringify(data);
      }
      let res = await axios.post(`${host}${api}`, data, {
        headers,
      });
      return res.data;
    }
    default: {
      const encode = encodeURI(data);
      const apistr = data ? `${host}${api}?${encode}` : `${host}${api}`
      let res = await axios.get(apistr, {
        headers
      });
      console.log(res)
      return res.data;
    }
  }
};
// export const launch = async (
//   method,
//   api,
//   data,
//   host,
//   headers = {
//     "content-type": "application/json",
//   }
// ) => {
//   switch (method) {
//     case Method.PUT: {
//       let res = await fetch(`${host}${api}`, {
//         method: Method.PUT,
//         headers,
//         body: JSON.stringify(data),
//       });
//       return await res.json();
//     }
//     case Method.DELETE: {
//       let res = await fetch(`${host}${api}?${encodeURI(data)}`, {
//         method: Method.DELETE,
//       });
//       return await res.json();
//     }
//     case Method.POST: {
//       if (!headers["content-type"].includes("multipart")) {
//         data = JSON.stringify(data);
//       }
//       let res = await fetch(`${host}${api}`, {
//         method: Method.POST,
//         headers,
//         body: data
//       });
//       return await res.json();
//     }
//     default: {
//       const encode = encodeURI(data);
//       let res = await fetch(`${host}${api}?${encode}`, {
//         method: Method.GET,
//       });
//       return await res.json();
//     }
//   }
// };

